package io.adrainty.gbatis.util;

import io.adrainty.gbatis.exception.CoreException;

import java.lang.reflect.Field;

/**
 * @author adrainty
 * @version v1.0.0
 * @since 2024/1/17 12:06
 */
public class ReflectUtil {

    private ReflectUtil() {}

    public static void setFieldValue(Object o, String field, Object value) {
        try {
            Field objectField = o.getClass().getDeclaredField(field);
            objectField.setAccessible(true);
            objectField.set(o, value);
        } catch (Exception e) {
            throw new CoreException(String.format("cannot set [%s] to [%s]", value, o.getClass().getSimpleName()));
        }
    }

    public static boolean hasField(Object o, String field) {
        try {
            o.getClass().getDeclaredField(field);
            return true;
        } catch (NoSuchFieldException e) {
            return false;
        }
    }

    public static String getFieldValue(Object o, String field) {
        try {
            Field objectField = o.getClass().getDeclaredField(field);
            objectField.setAccessible(true);
            return objectField.get(o).toString();
        } catch (Exception e) {
            throw new CoreException(String.format("cannot get [%s] value [%s]", o.getClass().getSimpleName(), field));
        }
    }

}
